package org.itboys.mobile.controller.mobile;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.kitchen.util.MobileSignUtils;
import org.itboys.mobile.dto.count.KitchenCountDto;
import org.itboys.mobile.entity.mongo.SundayAddress;
import org.itboys.mobile.service.mongo.mobile.SundayMobileAddressService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zzq
 * 时间：2017年5月9日
 * 描述：花果山（农厨）_移动端_收货地址_controller
 */
@Controller
@RequestMapping("/sunday/mobile/address")
public class SundayMobileAddressController extends BaseController{
    @Autowired
    private SundayMobileAddressService addressService;


    /**
     * 查询用户所有收货地址
     * @param request
     * @param response
     * @param

     */
    @RequestMapping(value="/select", method=RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】查找当前用户所有收货地址（也是获取用户的小区*****）。不分页")
    public void select(
            HttpServletRequest request,
            HttpServletResponse response,

            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try {
            Long memberId = AccountIdHoldUtils.getMemberId();
            List<SundayAddress> result =addressService.selectAddress(memberId);
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgResultDO(result,CommonConstants.SUCCESS));
        } catch (Exception e) {

            String msg ="";
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErroException")){
                msg=e.getMessage();
            }else{
                msg= CommonConstants.ERROMSG;
                logger.info("/sunday/mobile/address/select--------"+e);
            }
            e.printStackTrace();
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgCodeResultDO(CommonConstants.FAIL_CODE,msg));
        }
    }
    /**
     * 保存或者修改收货地址
     * @param request
     * @param response
     * @param id
     * @param
     * @param villageId
     * @param receiveName
     * @param receiveMobile
     * @param receiveAddress
     */
    @RequestMapping(value="/save", method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】保存新增或更新用户地址")
    public void save(HttpServletRequest request,
                     HttpServletResponse response,
                     @ApiParam(required=true, name="id", value="地址id。新增时传入0")@RequestParam(value = "id", required = false)Long id,
                     @ApiParam(required=false, name="villageId", value="小区id。用户版传入")@RequestParam(value = "villageId", required = false)Long villageId,
                     @ApiParam(required=true, name="receiveName", value="收货人姓名")@RequestParam(value = "receiveName", required = true)String receiveName,
                     @ApiParam(required=true, name="receiveMobile", value="手机号码")@RequestParam(value = "receiveMobile", required = true)String receiveMobile,
                     @ApiParam(required=false, name="provinceId", value="省ID。管理版传入")@RequestParam(value = "provinceId", required = false)Long provinceId,
                     @ApiParam(required=false, name="provinceName", value="省名称。管理版传入")@RequestParam(value = "provinceName", required = false)String provinceName,
                     @ApiParam(required=false, name="cityId", value="市ID。管理版传入")@RequestParam(value = "cityId", required = false)Long cityId,
                     @ApiParam(required=false, name="cityName", value="市名称。管理版传入")@RequestParam(value = "cityName", required = false)String cityName,
                     @ApiParam(required=false, name="districtId", value="区县ID。管理版传入")@RequestParam(value = "districtId", required = false)Long districtId,
                     @ApiParam(required=false, name="districtName", value="区县名称。管理版传入")@RequestParam(value = "districtName", required = false)String districtName,
                     @ApiParam(required=true, name="receiveAddress", value="详细地址")@RequestParam(value = "receiveAddress", required = true)String receiveAddress,
                     @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                     @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try{
           /* Map<String, Object> param =new HashMap<String,Object>();
            param.put("id",id);
            param.put("villageId",villageId);
            param.put("receiveName",receiveName);
            param.put("receiveMobile",receiveMobile);
            param.put("provinceId",provinceId);
            param.put("provinceName",provinceName);
            param.put("cityId",cityId);
            param.put("cityName",provinceId);
            param.put("districtId",districtId);
            param.put("districtName",districtName);
            param.put("receiveAddress",receiveAddress);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/

            Long memberId = AccountIdHoldUtils.getMemberId();
            addressService.saveAddress(id,memberId,villageId,receiveName,receiveMobile,provinceId,provinceName,cityId,cityName,districtId,districtName,receiveAddress);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/address/save----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    /**
     * 设置默认地址
     * @param request
     * @param response
     * @param
     * @param addressId
     */
    @RequestMapping(value="/setDefault", method=RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】设置当前地址为默认地址")
    public void setDefault(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required=true, name="addressId", value="地址id")@RequestParam(value = "addressId", required = true)Long addressId,
            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try{
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("addressId",addressId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            addressService.setDefaultAddress(addressId, memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/address/setDefault----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    /**
     * 单个删除收货地址
     * @param request
     * @param response
     * @param addressId
     */
    @RequestMapping(value="/delete", method=RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】删除地址")
    public void delete(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required=true, name="addressId", value="地址id")@RequestParam(value = "addressId", required = true)Long addressId,

            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){

        try{
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("addressId",addressId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }


            Long memberId = AccountIdHoldUtils.getMemberId();
            addressService.delete(addressId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/address/delete----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
}
